package com.ruyiadmin.springcloud.producer.service.impls.system;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruyiadmin.springcloud.producer.common.beans.system.SystemCacheConfig;
import com.ruyiadmin.springcloud.producer.common.core.system.entities.QueryResult;
import com.ruyiadmin.springcloud.producer.common.components.core.RuYiRedisComponent;
import com.ruyiadmin.springcloud.producer.domain.dto.system.SysAreaDTO;
import com.ruyiadmin.springcloud.producer.domain.entity.system.SysArea;
import com.ruyiadmin.springcloud.producer.repository.system.ISysAreaRepository;
import com.ruyiadmin.springcloud.producer.service.iservices.system.ISysAreaService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.modelmapper.ModelMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 行政区域 服务实现类
 * </p>
 *
 * @author RuYiAdmin
 * @since 2022-07-11
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class SysAreaServiceImpl extends ServiceImpl<ISysAreaRepository, SysArea> implements ISysAreaService {

    //region 实现类私有属性

    private final RuYiRedisComponent redisUtils;
    private final ModelMapper modelMapper;
    private final SystemCacheConfig systemCacheConfig;

    //endregion

    //region 加载行政区域缓存

    /**
     * 加载行政区域缓存
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void loadSysAreaCache() {
        List<SysAreaDTO> areas = new ArrayList<>();
        List<SysArea> list = this.list();
        for (SysArea area : list) {
            areas.add(this.modelMapper.map(area, SysAreaDTO.class));
        }
        this.redisUtils.set(systemCacheConfig.getAreaCacheName(), JSON.toJSONString(areas));
        log.info("RuYiAdmin sys areas cache loaded");
    }

    //endregion

    //region 清理行政区域缓存

    /**
     * 清理行政区域缓存
     */
    @Override
    public void clearSysAreaCache() {
        this.redisUtils.del(systemCacheConfig.getAreaCacheName());
        log.info("RuYiAdmin sys areas cache cleared");
    }

    //endregion

    //region 获取行政区域树形结构

    /**
     * 获取行政区域树形结构
     *
     * @return QueryResult
     */
    @Override
    public QueryResult<SysAreaDTO> getAreaTreeNodes() {

        Object value = this.redisUtils.get(systemCacheConfig.getAreaCacheName());
        List<SysAreaDTO> areas = JSON.parseArray(value.toString(), SysAreaDTO.class);

        List<SysAreaDTO> parentAreas = areas.stream().filter(t -> t.getParentAreaCode().equals("0")).
                sorted(Comparator.comparing(SysAreaDTO::getAreaCode)).collect(Collectors.toList());

        for (SysAreaDTO item : parentAreas) {
            this.getAreaChildren(item, areas);
        }

        List<SysAreaDTO> result = new ArrayList<>(parentAreas);

        return QueryResult.success(result.size(), result);
    }

    //endregion

    //region 实现类私有方法

    /**
     * 获取区域子集
     *
     * @param root  父节点
     * @param areas 集合
     */
    private void getAreaChildren(SysAreaDTO root, List<SysAreaDTO> areas) {
        List<SysAreaDTO> list = areas.stream().filter(t -> t.getParentAreaCode().equals(root.getAreaCode())).
                collect(Collectors.toList());
        if (list.size() > 0) {
            root.setChildren(new ArrayList<>());
            root.setChildren(list.stream().sorted(Comparator.comparing(SysAreaDTO::getAreaCode))
                    .collect(Collectors.toList()));
            for (SysAreaDTO item : list) {
                this.getAreaChildren(item, areas);
            }
        }
    }

    //endregion

}
